package extensions;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;

public class BroadcastThread extends Thread implements Runnable{

	private static final String BROADCAST_GROUP = "230.1.2.3";
	private static final int LISTENING_PORT = 4447;
	private static final int RANDOM_SLEEP = 5000;
	
	private MulticastSocket _socket;
	
	private boolean _run = true;
	
	public BroadcastThread() throws IOException
	{
		super("BroadcastThread");
		
		System.out.println("Starting BroadcastThread on "+BROADCAST_GROUP+":"+LISTENING_PORT);
		
		_socket = new MulticastSocket(LISTENING_PORT);
	}
	
	/**
	 * Breaks the infinite loop.
	 */
	public void stopRunning()
	{
		_run = false;
	}
	
	private static final byte[] BUFFER = new byte[]{1};
	
	@Override
	public void run()
	{
		
		System.out.println("Broadcasting packets on "+BROADCAST_GROUP+":"+LISTENING_PORT);
		try {
			InetAddress group = InetAddress.getByName(BROADCAST_GROUP);
			
			while (_run)
			{
				DatagramPacket packet = new DatagramPacket(BUFFER, BUFFER.length, group, LISTENING_PORT);
				
				_socket.send(packet);
				try {
					sleep((long)(Math.random()*RANDOM_SLEEP));
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
